#include "common.hpp"
#include <sys/wait.h>

static void Getmessage(int fd)
{
   char buff[SIZE];
   Log("处理数据开始", Test) << "[" << getpid() << "] "<< " step 3 " << endl;
   while (1)
   {
    memset(buff, '\0', sizeof(buff));
    ssize_t byte = read(fd, buff, sizeof(buff) - 1);
    if (byte > 0)
    {
        cout << "[" << getpid() << "] " << buff << endl;
    }else if ( byte == 0)
    {
        cout << " write close " << endl;
        break;
    }else
    {
        perror(" read fail");
        cout << "[" << getpid() << "] " << " read error "  << endl;
        break;
    }
   }
}


int main()
{
   // 1. 创建命名管道
   if (mkfifo(PipeAddress.c_str(), MOODE) < 0 )
   {
      perror( " mkfifo fail ");
   }

   Log("创建命名管道成功", debug) << "step 1" << endl;
   // 2. 文件操作
   int fd = open(PipeAddress.c_str(), O_RDONLY);
   if (!fd)
   {
      perror(" open fail");
      exit(-1);
   }
    Log("文件操作成功", debug) << "step 2" << endl;

   pid_t id;
   vector<int> FdList;
   for (int i = 0; i < CHNUMS; i++)
   {
       id = fork();
       if (id == 0)
       {
           Getmessage(fd);
           exit(1);  // 子进程完美退出，等待父进程接收
       }
   }

   // 父进程接受子进程退出
   int status = 0;
   for (int i = 0; i < CHNUMS; i++)
   {
       // waitpid(FdList[i], nullptr, 0);  这样子写会些坑，不知道哪一个子进程先状态改变
       waitpid(-1, &status, 0); // -1则是随机等待一个子进程状态改变
   } 
   
   // 4. 关闭文件
   close(fd);
   unlink(PipeAddress.c_str());
   Log("关闭文件", warning) << "step 4" << endl;
   return 0;
}
 






